Top Tags

Kubernetes CLI Handbook

Quick reference for essential kubectl commands — cluster management, pod operations, deployments, services, debugging, configs, logs, and more.

Setup & Autocomplete

Install kubectl

bash
1# macOS (Homebrew)
2brew install kubectl
3
4# Linux (apt)
5sudo apt update && sudo apt install -y kubectl
6
7# Verify installation
8kubectl version --client

Shell Autocomplete

bash
1# Bash
2source <(kubectl completion bash)
3echo "source <(kubectl completion bash)" >> ~/.bashrc
4
5# Zsh
6source <(kubectl completion zsh)
7echo '[[ $commands[kubectl] ]] && source <(kubectl completion zsh)' >> ~/.zshrc
8
9# Fish (requires kubectl 1.23+)
10echo 'kubectl completion fish | source' > ~/.config/fish/completions/kubectl.fish

Useful Aliases

bash
1alias k=kubectl
2complete -o default -F __start_kubectl k # Bash autocomplete for alias
3
4alias kx='kubectl config use-context'
5alias kn='kubectl config set-context --current --namespace'
6alias kga='kubectl get all'
7alias kgp='kubectl get pods'
8alias kgs='kubectl get svc'
9alias kgn='kubectl get nodes'

Shorthand Flags

bash
1kubectl -A # Short for --all-namespaces
2kubectl -n my-ns # Short for --namespace my-ns
3kubectl -o wide # Short for --output wide
4kubectl -o yaml # Short for --output yaml
5kubectl -w # Short for --watch

Important Paths & Config Files

Kubeconfig & Cluster Configuration

bash
1~/.kube/config # Default kubeconfig file (contexts, clusters, users)
2/etc/kubernetes/ # Kubernetes cluster config (on control plane nodes)
3/etc/kubernetes/admin.conf # Admin kubeconfig (created by kubeadm)
4/etc/kubernetes/manifests/ # Static pod manifests (kube-apiserver, etcd, etc.)
5/etc/kubernetes/pki/ # Cluster certificates and keys

Container Runtime Paths

bash
1/var/log/containers/ # Container log files (symlinks)
2/var/log/pods/ # Pod log files organized by pod UID
3/var/lib/kubelet/ # Kubelet data directory
4/var/lib/kubelet/config.yaml # Kubelet configuration
5/var/lib/etcd/ # etcd data directory
6/var/run/containerd/ # Containerd runtime socket

Environment Variables

bash
1KUBECONFIG=~/.kube/config # Path to kubeconfig (can be colon-separated list)
2KUBECONFIG=~/.kube/config:~/.kube/config2 # Use multiple kubeconfig files
3KUBE_EDITOR="nano" # Set editor for kubectl edit

Context & Cluster Management

View & Switch Context

bash
1kubectl config view # Show merged kubeconfig settings
2kubectl config view --raw # Show full config with secrets/certs
3kubectl config current-context # Display the current context
4kubectl config get-contexts # List all contexts
5kubectl config get-contexts -o name # List context names only
6kubectl config use-context my-cluster # Switch to a different context
7kubectl config set-context --current --namespace=my-ns # Set default namespace

Manage Clusters & Users

bash
1kubectl config set-cluster my-cluster --server=https://1.2.3.4:6443 # Add cluster
2kubectl config set-cluster my-cluster --proxy-url=http://proxy:8080 # Set proxy
3kubectl config set-credentials user1 --username=admin --password=pass # Add user
4kubectl config unset users.foo # Delete a user entry
5kubectl config delete-context my-context # Delete a context

Cluster Info

bash
1kubectl cluster-info # Display master and services addresses
2kubectl cluster-info dump # Dump full cluster state to stdout
3kubectl cluster-info dump --output-directory=/tmp/cluster-state # Dump to directory
4kubectl version # Show client and server versions
5kubectl api-versions # List all API versions
6kubectl api-resources # List all resource types with shortnames
7kubectl api-resources --namespaced=true # Only namespaced resources
8kubectl api-resources --namespaced=false # Only cluster-scoped resources
9kubectl api-resources --verbs=list,get # Resources supporting list and get

Namespaces

Manage Namespaces

bash
1kubectl get namespaces # List all namespaces
2kubectl get ns # Short form
3kubectl create namespace my-ns # Create a namespace
4kubectl delete namespace my-ns # Delete a namespace (and all resources in it!)
5kubectl config set-context --current --namespace=my-ns # Set default namespace
6kubectl get all -n my-ns # List all resources in a namespace
7kubectl get all -A # List all resources across all namespaces

Creating & Applying Resources

bash
1kubectl apply -f manifest.yaml # Create or update resource(s)
2kubectl apply -f file1.yaml -f file2.yaml # Apply multiple files
3kubectl apply -f ./manifests/ # Apply all manifests in a directory
4kubectl apply -f https://example.com/m.yaml # Apply from URL
5kubectl diff -f manifest.yaml # Preview changes before applying

Create Resources (Imperative)

bash
1kubectl create deployment nginx --image=nginx # Create deployment
2kubectl create service clusterip my-svc --tcp=80:8080 # Create service
3kubectl create namespace my-ns # Create namespace
4kubectl create configmap my-config --from-literal=key=value # Create configmap
5kubectl create secret generic my-secret --from-literal=pwd=s3cr3t # Create secret
6kubectl create job my-job --image=busybox -- echo "Hello" # Create job
7kubectl create cronjob my-cj --image=busybox --schedule="*/5 * * * *" -- echo "Hi" # Create cronjob

Dry Run & Generate YAML

bash
1kubectl create deployment nginx --image=nginx --dry-run=client -o yaml # Generate YAML without creating
2kubectl run nginx --image=nginx --dry-run=client -o yaml > pod.yaml # Generate pod YAML to file
3kubectl explain pods # Get documentation for pod manifest fields
4kubectl explain pods.spec.containers # Explain a specific field

Viewing & Inspecting Resources

Get Resources (Basic)

bash
1kubectl get pods # List pods in current namespace
2kubectl get pods -A # List pods in all namespaces
3kubectl get pods -o wide # List pods with extra info (node, IP)
4kubectl get pods -o yaml # Output as YAML
5kubectl get pods -o json # Output as JSON
6kubectl get pods -o name # Output resource names only
7kubectl get pods --show-labels # Show labels for all pods
8kubectl get pods -w # Watch for changes in real-time
9kubectl get all # List all resource types in namespace

Get Specific Resource Types

bash
1kubectl get nodes # List nodes
2kubectl get nodes -o wide # Nodes with extra info
3kubectl get deployments # List deployments
4kubectl get svc # List services
5kubectl get ep # List endpoints
6kubectl get rs # List replicasets
7kubectl get ds # List daemonsets
8kubectl get sts # List statefulsets
9kubectl get jobs # List jobs
10kubectl get cronjobs # List cronjobs
11kubectl get pv # List persistent volumes
12kubectl get pvc # List persistent volume claims
13kubectl get configmap # List configmaps
14kubectl get secret # List secrets
15kubectl get ingress # List ingresses
16kubectl get events --sort-by=.metadata.creationTimestamp # Events sorted by time
17kubectl events --types=Warning # Warning events only

Describe Resources (Detailed View)

bash
1kubectl describe pod my-pod # Detailed info about a pod
2kubectl describe node my-node # Detailed info about a node
3kubectl describe deployment my-dep # Detailed info about a deployment
4kubectl describe svc my-service # Detailed info about a service
5kubectl describe pvc my-pvc # Detailed info about a PVC

Filtering & Sorting

bash
1kubectl get pods -l app=nginx # Filter by label
2kubectl get pods -l 'app in (nginx,redis)' # Filter by label (set-based)
3kubectl get pods --field-selector=status.phase=Running # Filter by field
4kubectl get pods --sort-by='.status.containerStatuses[0].restartCount' # Sort by restarts
5kubectl get services --sort-by=.metadata.name # Sort by name
6kubectl get pv --sort-by=.spec.capacity.storage # Sort PVs by capacity
7kubectl get node --selector='!node-role.kubernetes.io/control-plane' # Exclude control plane

JSONPath & Custom Output

bash
1# Get pod IPs
2kubectl get pods -o jsonpath='{.items[*].status.podIP}'
3
4# Get node external IPs
5kubectl get nodes -o jsonpath='{.items[*].status.addresses[?(@.type=="ExternalIP")].address}'
6
7# Custom columns output
8kubectl get pods -o custom-columns='NAME:.metadata.name,STATUS:.status.phase,NODE:.spec.nodeName'
9
10# Get all images running in a cluster
11kubectl get pods -A -o=custom-columns='DATA:spec.containers[*].image'

Labels & Annotations

Managing Labels

bash
1kubectl label pods my-pod app=nginx # Add a label
2kubectl label pods my-pod app=redis --overwrite # Overwrite a label
3kubectl label pods my-pod app- # Remove a label
4kubectl get pods -l app=nginx # Select by label
5kubectl get pods --show-labels # Show all labels

Managing Annotations

bash
1kubectl annotate pods my-pod description="my app" # Add annotation
2kubectl annotate pods my-pod description- # Remove annotation

Deployments & Rollouts

Manage Deployments

bash
1kubectl create deployment nginx --image=nginx --replicas=3 # Create with replicas
2kubectl get deployments # List deployments
3kubectl describe deployment my-dep # Describe deployment
4kubectl delete deployment my-dep # Delete deployment

Rolling Updates & Rollbacks

bash
1kubectl set image deployment/my-dep nginx=nginx:1.25 # Update image
2kubectl rollout status deployment/my-dep # Watch rollout progress
3kubectl rollout history deployment/my-dep # View rollout history
4kubectl rollout undo deployment/my-dep # Rollback to previous version
5kubectl rollout undo deployment/my-dep --to-revision=2 # Rollback to specific revision
6kubectl rollout restart deployment/my-dep # Rolling restart
7kubectl rollout pause deployment/my-dep # Pause rollout
8kubectl rollout resume deployment/my-dep # Resume rollout

Scaling

bash
1kubectl scale deployment my-dep --replicas=5 # Scale to 5 replicas
2kubectl scale --replicas=3 -f deployment.yaml # Scale from file
3kubectl autoscale deployment my-dep --min=2 --max=10 --cpu-percent=80 # Autoscale
4kubectl get hpa # List horizontal pod autoscalers

Services & Networking

Expose & Manage Services

bash
1kubectl expose deployment my-dep --port=80 --target-port=8080 --type=ClusterIP # ClusterIP
2kubectl expose deployment my-dep --port=80 --target-port=8080 --type=NodePort # NodePort
3kubectl expose deployment my-dep --port=80 --target-port=8080 --type=LoadBalancer # LoadBalancer
4kubectl get svc # List services
5kubectl describe svc my-service # Service details
6kubectl delete svc my-service # Delete service

Port Forwarding

bash
1kubectl port-forward pod/my-pod 8080:80 # Forward pod port to local
2kubectl port-forward svc/my-service 8080:80 # Forward service port to local
3kubectl port-forward deploy/my-dep 8080:80 # Forward deployment port to local
4kubectl port-forward pod/my-pod 8080:80 --address=0.0.0.0 # Listen on all interfaces

DNS & Networking

bash
1# Service DNS format inside the cluster:
2# <service-name>.<namespace>.svc.cluster.local
3
4# Test DNS resolution from a pod
5kubectl run dns-test --image=busybox:1.28 --rm -it -- nslookup my-service.default.svc.cluster.local
6
7# Get endpoints for a service
8kubectl get endpoints my-service

Pods & Containers

Run Pods

bash
1kubectl run nginx --image=nginx # Run a pod
2kubectl run nginx --image=nginx -n my-ns # Run in specific namespace
3kubectl run debug --image=busybox:1.28 -it --rm -- sh # Temporary interactive pod
4kubectl run nginx --image=nginx --dry-run=client -o yaml # Generate YAML only

Exec Into Containers

bash
1kubectl exec my-pod -- ls / # Run command in pod
2kubectl exec my-pod -- cat /etc/config/app.conf # Read a file
3kubectl exec -it my-pod -- /bin/sh # Interactive shell
4kubectl exec -it my-pod -- /bin/bash # Interactive bash shell
5kubectl exec my-pod -c my-container -- ls / # Specific container (multi-container)

Copy Files

bash
1kubectl cp /tmp/file.txt my-pod:/tmp/file.txt # Local → Pod
2kubectl cp my-pod:/tmp/file.txt /tmp/file.txt # Pod → Local
3kubectl cp /tmp/file.txt my-ns/my-pod:/tmp/file.txt # With namespace
4kubectl cp /tmp/file.txt my-pod:/tmp/file.txt -c my-container # Specific container

Pod Management

bash
1kubectl delete pod my-pod # Delete a pod
2kubectl delete pod my-pod --now # Delete immediately (no grace period)
3kubectl delete pod my-pod --grace-period=0 --force # Force delete
4kubectl delete pods -l app=nginx # Delete by label
5kubectl -n my-ns delete pod,svc --all # Delete all pods and services

Logs & Debugging

Viewing Logs

bash
1kubectl logs my-pod # Pod logs (stdout)
2kubectl logs my-pod --previous # Logs from previous container instance
3kubectl logs my-pod -c my-container # Specific container logs
4kubectl logs -f my-pod # Stream/follow logs
5kubectl logs -f my-pod -c my-container # Stream specific container logs
6kubectl logs my-pod --tail=100 # Last 100 lines
7kubectl logs my-pod --since=1h # Logs from last hour
8kubectl logs my-pod --since=5m # Logs from last 5 minutes
9kubectl logs my-pod --timestamps # Show timestamps
10kubectl logs -l app=nginx # Logs from all pods with label
11kubectl logs -l app=nginx --all-containers # All containers with label
12kubectl logs deploy/my-dep # Logs from deployment
13kubectl logs job/my-job # Logs from a job

Debugging Pods

bash
1kubectl describe pod my-pod # Full pod details, events, conditions
2kubectl get pod my-pod -o yaml # Full YAML manifest
3kubectl get events --field-selector involvedObject.name=my-pod # Events for specific pod
4
5# Debug with ephemeral container
6kubectl debug my-pod -it --image=busybox:1.28 # Attach debug container to pod
7kubectl debug my-pod -it --image=nicolaka/netshoot # Network debugging tools
8kubectl debug node/my-node -it --image=busybox:1.28 # Debug a node

Troubleshooting Checklist

bash
1# Pod stuck in Pending?
2kubectl describe pod my-pod # Check Events section for scheduling issues
3kubectl get events -n my-ns # Check namespace events
4
5# Pod in CrashLoopBackOff?
6kubectl logs my-pod --previous # Check previous container's logs
7kubectl describe pod my-pod # Check exit code and events
8
9# Service not reachable?
10kubectl get endpoints my-service # Check if endpoints are populated
11kubectl describe svc my-service # Verify selector matches pod labels
12kubectl get pods -l <selector-from-svc> # Confirm matching pods exist
13
14# Check resource usage
15kubectl top pods # CPU/Memory per pod (requires metrics-server)
16kubectl top nodes # CPU/Memory per node
17kubectl top pod my-pod --containers # Per-container metrics

ConfigMaps & Secrets

ConfigMaps

bash
1kubectl create configmap my-config --from-literal=key1=value1 --from-literal=key2=value2
2kubectl create configmap my-config --from-file=config.txt # From file
3kubectl create configmap my-config --from-file=configs/ # From directory
4kubectl create configmap my-config --from-env-file=.env # From env file
5kubectl get configmaps # List configmaps
6kubectl describe configmap my-config # View configmap details
7kubectl get configmap my-config -o yaml # View as YAML
8kubectl delete configmap my-config # Delete configmap

Secrets

bash
1kubectl create secret generic my-secret --from-literal=password=s3cr3t
2kubectl create secret generic my-secret --from-file=ssh-key=~/.ssh/id_rsa # From file
3kubectl create secret tls my-tls --cert=tls.crt --key=tls.key # TLS secret
4kubectl get secrets # List secrets
5kubectl describe secret my-secret # View metadata (not data)
6kubectl get secret my-secret -o yaml # View with base64-encoded data
7kubectl get secret my-secret -o jsonpath='{.data.password}' | base64 -d # Decode a secret value
8kubectl delete secret my-secret # Delete secret

Persistent Storage

PersistentVolumes & PersistentVolumeClaims

bash
1kubectl get pv # List persistent volumes
2kubectl get pvc # List persistent volume claims
3kubectl describe pv my-pv # Describe PV
4kubectl describe pvc my-pvc # Describe PVC
5kubectl delete pvc my-pvc # Delete PVC
6kubectl get storageclass # List storage classes
7kubectl describe storageclass my-sc # Describe storage class

Node Management

View & Manage Nodes

bash
1kubectl get nodes # List all nodes
2kubectl get nodes -o wide # Nodes with IPs, OS, kernel info
3kubectl describe node my-node # Full node details
4kubectl top node # Node resource usage
5kubectl top node my-node # Specific node usage

Maintenance & Scheduling

bash
1kubectl cordon my-node # Mark node as unschedulable
2kubectl uncordon my-node # Mark node as schedulable again
3kubectl drain my-node # Evict pods for maintenance
4kubectl drain my-node --ignore-daemonsets --delete-emptydir-data # Force drain

Taints & Tolerations

bash
1kubectl taint nodes my-node key=value:NoSchedule # Add taint
2kubectl taint nodes my-node key=value:NoSchedule- # Remove taint
3
4# View existing taints
5kubectl get nodes -o='custom-columns=NodeName:.metadata.name,TaintKey:.spec.taints[*].key,TaintValue:.spec.taints[*].value,TaintEffect:.spec.taints[*].effect'

Resource Updates & Patching

Edit Resources

bash
1kubectl edit deployment my-dep # Open in default editor
2KUBE_EDITOR="nano" kubectl edit svc my-svc # Use specific editor

Update Resources

bash
1kubectl set image deployment/my-dep nginx=nginx:1.25 # Update container image
2kubectl set resources deployment/my-dep -c=nginx --limits=cpu=200m,memory=256Mi # Set resource limits
3kubectl replace -f manifest.yaml # Replace resource from file
4kubectl replace --force -f manifest.yaml # Force replace (delete + recreate)

Patch Resources

bash
1# Strategic merge patch
2kubectl patch deployment my-dep -p '{"spec":{"replicas":3}}'
3
4# JSON patch
5kubectl patch pod my-pod --type='json' -p='[{"op":"replace","path":"/spec/containers/0/image","value":"nginx:1.25"}]'
6
7# Patch a node (mark unschedulable)
8kubectl patch node my-node -p '{"spec":{"unschedulable":true}}'
9
10# Patch scale subresource
11kubectl patch deployment my-dep --subresource='scale' --type='merge' -p '{"spec":{"replicas":5}}'

Deleting Resources

Delete Commands

bash
1kubectl delete -f manifest.yaml # Delete from file
2kubectl delete pod my-pod # Delete specific pod
3kubectl delete pod my-pod --now # No grace period
4kubectl delete pod,svc my-pod my-svc # Delete pod and service
5kubectl delete pods,services -l app=nginx # Delete by label
6kubectl -n my-ns delete pod,svc --all # Delete all in namespace
7kubectl delete namespace my-ns # Delete entire namespace

RBAC & Security

View Roles & Bindings

bash
1kubectl get roles -A # List roles in all namespaces
2kubectl get clusterroles # List cluster-wide roles
3kubectl get rolebindings -A # List role bindings
4kubectl get clusterrolebindings # List cluster role bindings
5kubectl describe clusterrole admin # Describe a cluster role
6kubectl get serviceaccount -A # List service accounts

Check Permissions

bash
1kubectl auth can-i create pods # Check if you can create pods
2kubectl auth can-i '*' '*' # Check if you have full access
3kubectl auth can-i create pods --as=user1 # Check as another user
4kubectl auth can-i list secrets --as=system:serviceaccount:my-ns:my-sa # Check as service account
5kubectl auth whoami # Show current authentication info

Resource Quotas & Limits

View Resource Usage

bash
1kubectl top pods # Pod CPU/Memory (requires metrics-server)
2kubectl top pods -A # All namespaces
3kubectl top pods --sort-by=cpu # Sort by CPU
4kubectl top pods --sort-by=memory # Sort by memory
5kubectl top nodes # Node CPU/Memory
6kubectl top pod my-pod --containers # Per-container metrics

Quotas & Limits

bash
1kubectl get resourcequotas -A # List resource quotas
2kubectl describe resourcequota my-quota # View quota details
3kubectl get limitranges -A # List limit ranges
4kubectl describe limitrange my-limits # View limit range details

Output Formatting

Common Output Flags

FlagDescription
-o yamlYAML format
-o jsonJSON format
-o wideExtra details (node, IP)
-o nameResource names only
-o jsonpath='{...}'Extract specific fields
-o custom-columns=...Custom table columns
-o go-template=...Go template formatting
--sort-by=...Sort by a field
--no-headersOmit column headers

Verbosity Levels

FlagDescription
--v=0Always visible to operators
--v=1Reasonable default
--v=2Useful steady state info (recommended)
--v=4Debug level
--v=6Display requested resources
--v=7Display HTTP request headers
--v=9Full HTTP request content

Common Resource Shortnames

ShortFull Resource
popods
svcservices
deploydeployments
rsreplicasets
dsdaemonsets
stsstatefulsets
nsnamespaces
nonodes
pvpersistentvolumes
pvcpersistentvolumeclaims
cmconfigmaps
saserviceaccounts
ingingresses
ependpoints
scstorageclasses
hpahorizontalpodautoscalers
cjcronjobs
netpolnetworkpolicies